package com.rentalcar.rental_car.controller;

import com.rentalcar.rental_car.entity.Result;
import com.rentalcar.rental_car.entity.Role;
import com.rentalcar.rental_car.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@Slf4j
@RequestMapping("role")
public class RoleController {
    @Autowired
    RoleService roleService;
    @PostMapping("/roleList")
    public Result roleList(){
        try {
            log.info("查询所有管理员");
            return Result.success(roleService.getRoleAll());
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("查询失败");
        }
    }

    @PostMapping("/selectName")
    public Result selectName(@RequestBody Role role){
        try {
            log.info("查找"+role.getRname()+"的管理员");
            return Result.success(roleService.selectByName(role.getRname()));
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("查询失败");
        }
    }
    @PostMapping("/register")
    public Result register(@RequestBody Role role){
        try {
            log.info("注册一个管理员账号");
            return roleService.add(role);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("注册失败");
        }
    }
    @PostMapping("/updateRole")
    public Result updateRole(@RequestBody Role role){
        try {
            log.info("更新"+role.getRoleKey()+"管理员的信息");
            roleService.update(role);
            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("更新失败");
        }
    }
    @PostMapping("/loginCheckRole")
    public Result loginCheck(@RequestBody Role role){
        try {
            log.info(role.getRoleKey()+"管理员正在登录");
            Result result = roleService.loginCheck(role);
            if(result.getCode()==1){
                return Result.success(result.getData());
            }
            else if(result.getMsg().equals("账号密码错误")){
                return result;
            }
            return Result.fail("登录失败");
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("登录失败");
        }
    }
    @PostMapping("/logOutRole")
    public Result logOut(@RequestBody Role role){
        try {
            log.info(role.getRoleKey()+"管理员退出登录");
            return roleService.logOut(role);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("退出失败");
        }
    }
}
